import re
import requests
from api.base import *
from common.logger import logger
from common.retcode import RetCode
from common.encrypt import API
from common.types import UserInfo

class UserAction(BaseAction):
	def __init__(self, sess_wp: SessionWrapper):
		super(UserAction, self).__init__(sess_wp)

	def get_user_infos(self):
		"""获取登录用户信息"""
		url = self._host_url + "/v2/getLoginedInfos.action"
		resp = self._get(url)
		if not resp:
			logger.error("Get user info: network error!")
			return RetCode.FAILED, None
		resp = resp.json()
		if resp is None or 'userId' not in resp:
			logger.error("Get user info: invaild response!")
			return RetCode.FAILED, None
		id_ = resp['userId']
		account = resp['userAccount']
		nickname = resp['nickname'] if 'nickname' in resp else ''
		used = resp['usedSize']
		quota = resp['quota']
		vip = resp['superVip'] if 'superVip' in resp else ''
		endTime = resp['superEndTime'] if 'superEndTime' in resp else ''
		beginTime = resp['superBeginTime'] if 'superBeginTime' in resp else ''
		domain = resp['domainName'] if 'domainName' in resp else ''
		return RetCode.SUCCESS, UserInfo(id=id_, account=account, nickname=nickname, used=used, quota=quota,
						vip=vip, endTime=endTime, beginTime=beginTime, domain=domain)

	def user_sign(self):
		"""签到 + 抽奖"""

		result = {
			'sign': '',
			'prize': []
		}

		sign_url = API + '//mkt/userSign.action'
		headers = {
			'SessionKey': self._sess_wp.get_session_key()
		}
		resp = requests.get(sign_url, headers=headers, verify=False)
		if not resp:
			result['sign'] = "Sign: network error!"
		elif resp.status_code != requests.codes.ok:
			result['sign'] = f"签到失败 {resp}, {headers}"
		else:
			msg = re.search(r'获得.+?空间', resp.text)
			msg = msg.group() if msg else ""
			result['sign'] = f"{msg}"

		url = 'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action'
		params = {
			'taskId': 'TASK_SIGNIN',
			'activityId': 'ACT_SIGNIN'
		}
		prize_list = result['prize']
		for i in range(1, 3):
			resp = self._get(url, params=params)
			if not resp:
				prize_list.append("Sign: network error!")
			else:
				resp_json = resp.json()
				if resp_json:
					if 'errorCode' in resp_json:
						prize_list.append("次数已用完")
					else:
						prize_list.append(f"{resp_json['prizeName']}")
				else:
					prize_list.append("下次努力")
			params.update({'taskId': 'TASK_SIGNIN_PHOTOS'})

		return result
